<?php

namespace app\common\model;

use think\Request;
use think\Model;
use addons\wxsaas\library\Wechat;

class Applet extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 定义字段类型
    protected $type = [
    ];
    protected $append = [
        'type'
    ];

    /**
     * 门店类型
     */
    public function getTypeAttr($value,$data)
    {
        $status = [10 => '微信小程序', 20 => '微信公众号'];
        return $status[$data['app_type']];
    }
    
    /**
     * 关联版本表
     */
    public function version()
    {
        return $this->belongsTo('app\\common\\model\\FormworkVersion','formwork_version_id','id')->order(['id' => 'desc']);
    }

    /**
     * 获取列表
     */
    public function getList($user_id=0)
    {
        // 筛选条件
        $filter = [];
        $user_id > 0 && $filter['user_id'] = $user_id;

        // 执行查询
        $list = $this->with(['version','version.formwork'])
            ->where($filter)
            ->order('id','desc')
            ->paginate(15, false, [
                'query' => Request::instance()->request()
            ]);
        return $list;
    }

    /**
     * 获取详情
     */
    public static function detail($id)
    {
        return self::get($id, ['version','version.formwork']);
    } 

    /**
     * 获取详情
     */
    public static function getAppid($app_id)
    {
        return self::where('app_id',$app_id)->find();
    }

    /**
     * 获取详情
     */
    public static function getUserName($user_name)
    {
        return self::where('user_name',$user_name)->find();
    }

    /**
     * 添加
     */
    public function add($data)
    {
        return $this->allowField(true)->save($data);
    }

    /**
     * 更新小程序设置
     */
    public function edit($data)
    {
        //如果是微信小程序
        if($this->app_type == 10){
            $wx = new Wechat;
            //添加服务器域名
            if(isset($data['api_domain']) AND $this->api_domain != $data['api_domain']){
                $result = $wx->setServeDomain($this->id,$data['api_domain']);
                if($result['errcode'] != 0){
                    $this->error = '服务器域名设置失败！code：'.$result['errcode'].',msg：'.$result['errmsg'];
                    return false;
                }
            }
            if(isset($data['signature']) AND $this->signature != $data['signature']){
                $result = $wx->setSignature($this->id,$data['signature']);
                if($result['errcode'] != 0){
                    $this->error = '简介设置失败！code：'.$result['errcode'].',msg：'.$result['errmsg'];
                    return false;
                }
            }
        }
        return $this->allowField(true)->save($data) !== false;
    }
}
